let { killApp } = require('./utils/killApp.js')

let scriptEngine = null
// 是否正在重启游戏脚本
let restarting = false

let enginesList = engines.all()
let currentEngineIdx = enginesList.indexOf(engines.myEngine())

enginesList.forEach((engine, idx) => {
    if(idx != currentEngineIdx) {
        engine.forceStop()
    }
})

function start() {
    if(scriptEngine) {
        toast("脚本正在运行中");    
    }else {
        toast("开始运行脚本");
        scriptEngine = engines.execScriptFile(files.path('./script.js'));
    }
}

function stop() {
    if(scriptEngine) {
        scriptEngine.getEngine().forceStop()
        sleep(100)
        scriptEngine = null
    }
}

//启用按键监听
events.observeKey();

//监听音量上键按下
events.onKeyDown("volume_up", function(event){
    start()
});

//监听音量上键按下
events.onKeyDown("volume_down", function(event){
    stop()
    toast("已停止游戏脚本");
});

events.onKeyDown("back", function(event){
    toast("已停止脚本");
    stop()
    engines.stopAll()
});

events.broadcast.on('detection', () => {
    if(!restarting) {
        console.log('开始重新');
        restarting = true
        // 停止游戏脚本操作
        stop()
        sleep(1000)

        killApp(app.getAppName('com.studiolb.tamingmaster.global'))
        sleep(1000)

        start()
        sleep(3000)
        restarting = false
    }
})

start()





